<template>
  <el-card class="data-card" shadow="never">
    <div slot="header" class="card-header">
      <div class="header-left">
        <i class="el-icon-s-help" />
        <span>校区开业辅导统计</span>
      </div>
      <div class="header-right">
        <el-select v-model="filterForm.brand" placeholder="选择品牌" size="small" style="width: 120px; margin-right: 8px;" @change="handleFilterChange">
          <el-option label="全部品牌" value="" />
          <el-option v-for="item in brandOptions" :key="item.enCode" :label="item.fullName" :value="item.enCode" />
        </el-select>
        <el-date-picker v-model="filterForm.dateRange" type="daterange" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期" format="yyyy-MM-dd" value-format="yyyy-MM-dd" size="small" style="width: 240px; margin-right: 8px;" @change="handleFilterChange" />

        <el-button size="small" icon="el-icon-refresh" :loading="loading" @click="refreshData">刷新</el-button>
      </div>
    </div>
    <div v-loading="loading" class="guidance-table-container">
      <el-table :data="pivotData" size="small" stripe border show-summary :summary-method="getPivotSummaries" sum-text="总计" class="report-table">
        <el-table-column prop="month" label="年月" min-width="100" align="center">
          <template slot-scope="scope">
            <span class="data-primary">{{ scope.row.month }}</span>
          </template>
        </el-table-column>
        <el-table-column v-for="area in areas" :key="area.code" :label="area.name" align="center">
          <el-table-column :prop="'area_' + area.code + '_campus'" label="校区数" min-width="80" align="center">
            <template slot-scope="scope">
              <span class="data-info">{{ scope.row['area_' + area.code + '_campus'] || 0 }}</span>
            </template>
          </el-table-column>
          <el-table-column :prop="'area_' + area.code + '_qualified'" label="达标数" min-width="80" align="center">
            <template slot-scope="scope">
              <span class="data-success">{{ scope.row['area_' + area.code + '_qualified'] || 0 }}</span>
            </template>
          </el-table-column>
          <el-table-column :prop="'area_' + area.code + '_rate'" label="达标率" min-width="90" align="center">
            <template slot-scope="scope">
              <span class="data-success">{{ formatRate(scope.row['area_' + area.code + '_rate']) }}</span>
            </template>
          </el-table-column>
        </el-table-column>
        <el-table-column label="汇总" align="center">
          <el-table-column prop="totalCampus" label="校区数汇总" min-width="100" align="center">
            <template slot-scope="scope">
              <span class="data-info">{{ scope.row.totalCampus || 0 }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="totalQualified" label="达标数汇总" min-width="100" align="center">
            <template slot-scope="scope">
              <span class="data-success">{{ scope.row.totalQualified || 0 }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="totalRate" label="达标率汇总" min-width="100" align="center">
            <template slot-scope="scope">
              <span class="data-success">{{ formatRate(scope.row.totalRate) }}</span>
            </template>
          </el-table-column>
        </el-table-column>
      </el-table>
    </div>
  </el-card>
</template>

<script>
import { getGuidanceStatisticsUnified } from '@/api/report/services'

export default {
  name: 'GuidanceStatisticsReport',
  props: {
    // 管理区域选项
    managementAreaOptions: {
      type: Array,
      default: () => []
    }
  },
  data() {
    // 获取当前年度时间范围
    const getCurrentYearRange = () => {
      const currentYear = new Date().getFullYear()
      const startDate = `${currentYear}-01-01`
      const endDate = `${currentYear}-12-31`
      return [startDate, endDate]
    }

    return {
      loading: false,
      pivotData: [],
      areas: [],
      brandOptions: [],

      filterForm: {
        brand: 'bell', // 默认选择贝尔安亲
        dateRange: getCurrentYearRange()
      }
    }
  },

  watch: {
    managementAreaOptions: {
      handler() {
        if (this.managementAreaOptions && this.managementAreaOptions.length > 0) {
          // managementAreaOptions已更新，重新构建区域列表
          this.buildAreasFromManagementOptions()
        }
      },
      immediate: true,
      deep: true
    }
  },

  mounted() {
    this.loadBrandOptions()
    this.loadGuidanceData()
  },
  methods: {
    /**
     * 加载开业辅导统计数据并构建透视表
     * - 安全解析筛选条件（品牌与日期范围），为空则使用当年默认范围（北京时间）
     * - 请求后端统一接口，解析并映射为表格行数据
     * - 构建管理区域列元数据，兼容后端返回的区域信息
     * - 计算指标并通知父组件数据更新
     * @returns {Promise<void>} 异步更新组件状态，无返回值
     */
    async loadGuidanceData() {
      this.loading = true

      try {
        // 构建查询参数
        const params = {}

        // 安全获取时间参数，确保有默认值
        const startDate = this.filterForm.dateRange && this.filterForm.dateRange[0] ? this.filterForm.dateRange[0] : this.getCurrentYearRange()[0]
        const endDate = this.filterForm.dateRange && this.filterForm.dateRange[1] ? this.filterForm.dateRange[1] : this.getCurrentYearRange()[1]

        if (startDate && startDate !== 'null' && startDate !== null && startDate !== '') {
          params.startDate = startDate
        }

        if (endDate && endDate !== 'null' && endDate !== null && endDate !== '') {
          params.endDate = endDate
        }

        // 添加品牌筛选参数
        if (this.filterForm.brand && this.filterForm.brand !== '') {
          params.brand = this.filterForm.brand
        }

        // 调用开业辅导统计接口
        const guidanceResponse = await getGuidanceStatisticsUnified(params)
        const responseData = guidanceResponse.data || guidanceResponse

        // 构建完整的管理区域列表并排序
        this.buildAreasFromManagementOptions()

        // 如果后端返回了管理区域列表，使用后端数据更新区域信息
        if (responseData.managementAreas) {
          // 更新areas中的后端数据，但保持排序
          this.areas.forEach(area => {
            const backendArea = responseData.managementAreas.find(ba => ba.code === area.code)
            if (backendArea) {
              area.name = backendArea.name || area.name
              // 保留其他后端数据
              Object.assign(area, backendArea)
            }
          })
        }

        // 直接使用后端返回的透视表数据
        if (responseData.pivotData) {
          this.pivotData = responseData.pivotData.map(item => ({
            month: item.month,
            totalCampus: Number(item.totalCampusCount || 0),
            totalQualified: Number(item.totalQualifiedCount || 0),
            totalRate: this.calculateRate(Number(item.totalQualifiedCount || 0), Number(item.totalCampusCount || 0)),
            ...this.processAreaData(item.areaData || {})
          }))
        } else {
          this.pivotData = []
        }

        // 计算开业辅导指标并通知父组件数据已更新
        this.calculateGuidanceMetrics()

        this.$emit('data-updated', {
          pivotData: this.pivotData,
          areas: this.areas
        })
      } catch (error) {
        this.$message.error('开业辅导统计数据加载失败')

        // 如果API调用失败，初始化空数据
        this.pivotData = []
        this.areas = []
      } finally {
        this.loading = false
      }
    },

    /**
     * 将后端返回的区域数据映射为透视表行的平铺字段
     * - 输入对象键为区域编码，值包含 campusCount 与 qualifiedCount
     * - 输出以 `area_{code}_campus` 与 `area_{code}_qualified` 命名的数值字段
     * @param {Object<string,{campusCount:number,qualifiedCount:number}>} areaData 区域数据对象
     * @returns {Object<string,number>} 映射后的平铺字段对象
     */
    processAreaData(areaData) {
      const result = {}
      Object.keys(areaData).forEach(areaKey => {
        const data = areaData[areaKey]
        result[`area_${areaKey}_campus`] = Number(data.campusCount || 0)
        result[`area_${areaKey}_qualified`] = Number(data.qualifiedCount || 0)
        result[`area_${areaKey}_rate`] = this.calculateRate(Number(data.qualifiedCount || 0), Number(data.campusCount || 0))
      })
      return result
    },

    /**
     * 获取当前年度时间范围（本地时间）
     * 返回 ['YYYY-01-01','YYYY-12-31']，用于筛选默认值
     * @returns {string[]} [startDate, endDate]
     */
    getCurrentYearRange() {
      const currentYear = new Date().getFullYear()
      const startDate = `${currentYear}-01-01`
      const endDate = `${currentYear}-12-31`
      return [startDate, endDate]
    },

    /**
     * 计算透视表总计行
     * - 第一列显示“总计”文本
     * - 其他数值列做求和，非数值列显示 N/A
     * @param {{columns:Array,data:Array}} param Element 表格汇总入参
     * @returns {Array} 汇总行数组
     */
    getPivotSummaries(param) {
      const { columns, data } = param
      const sums = []
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = '总计'
          return
        }
        const prop = column.property
        if (/^area_.+_rate$/.test(prop)) {
          const areaCode = prop.replace(/^area_/, '').replace(/_rate$/, '')
          const campusProp = `area_${areaCode}_campus`
          const qualifiedProp = `area_${areaCode}_qualified`
          const totalCampus = data.reduce((acc, row) => acc + Number(row[campusProp] || 0), 0)
          const totalQualified = data.reduce((acc, row) => acc + Number(row[qualifiedProp] || 0), 0)
          sums[index] = this.formatRate(this.calculateRate(totalQualified, totalCampus))
          return
        }
        if (prop === 'totalRate') {
          const totalCampus = data.reduce((acc, row) => acc + Number(row.totalCampus || 0), 0)
          const totalQualified = data.reduce((acc, row) => acc + Number(row.totalQualified || 0), 0)
          sums[index] = this.formatRate(this.calculateRate(totalQualified, totalCampus))
          return
        }
        const values = data.map(item => Number(item[prop]))
        if (!values.every(value => isNaN(value))) {
          sums[index] = values.reduce((prev, curr) => {
            const value = Number(curr)
            if (!isNaN(value)) {
              return prev + curr
            } else {
              return prev
            }
          }, 0)
        } else {
          sums[index] = 'N/A'
        }
      })
      return sums
    },

    calculateRate(qualified, campus) {
      const q = Number(qualified || 0)
      const c = Number(campus || 0)
      if (!c || isNaN(c)) return 0
      const rate = (q / c) * 100
      return Number(rate.toFixed(1))
    },

    formatRate(value) {
      const v = Number(value || 0)
      if (isNaN(v)) return '0%'
      return `${v}%`
    },

    /**
     * 计算开业辅导指标（示例逻辑）
     * - 计算总辅导数与增长率，作为示例指标
     * - 通过 metrics-updated 事件将指标发送给父组件
     */
    calculateGuidanceMetrics() {
      // 计算开业辅导总数（使用模拟数据，与原逻辑保持一致）
      const totalGuidance = 89 + Math.floor(Math.random() * 30) // 模拟数据：80-120之间

      // 模拟增长率（-12% 到 +12%）
      const guidanceGrowthRate = Math.floor(Math.random() * 25) - 12

      // 通过事件发送指标数据给父组件
      this.$emit('metrics-updated', {
        totalGuidance,
        guidanceGrowthRate
      })
    },

    /**
     * 处理筛选条件变化
     * - 触发数据重新加载并向父组件上报筛选条件
     */
    handleFilterChange() {
      this.loadGuidanceData()
      this.$emit('filter-change', this.filterForm)
    },

    /**
     * 加载品牌字典选项（启用项）
     * - 从 store 中拉取品牌字典并写入 brandOptions
     * - 失败时提示并回退为空数组
     * @returns {Promise<void>} 异步更新 brandOptions
     */
    async loadBrandOptions() {
      try {
        const res = await this.$store.dispatch('base/getDictionaryData', {
          sort: 'Brand'
        })
        this.brandOptions = res || []
      } catch (error) {
        this.brandOptions = []
        this.$message.error('品牌字典加载失败')
      }
    },

    /**
     * 从管理区域字典构建区域列元数据
     * - 仅保留启用的区域（enabledMark === 1）
     * - 同步排序码，默认 999
     */
    buildAreasFromManagementOptions() {
      if (!this.managementAreaOptions || this.managementAreaOptions.length === 0) {
        this.areas = []
        return
      }

      // 过滤出管理区域类型的选项（MANAGEMENT_AREA）
      const managementAreas = this.managementAreaOptions.filter(
        option => option.enabledMark === 1 // 只包含启用的区域
      )

      // 过滤出管理区域类型的选项

      // 构建区域列表
      this.areas = managementAreas.map(option => {
        return {
          code: option.enCode,
          name: option.fullName,
          sortCode: this.getRegionSort(option.enCode)
        }
      })
    },

    /**
     * 根据区域编码获取排序码
     * - 若找不到或非数值则回退为 999
     * @param {string} regionCode 区域编码
     * @returns {number} 排序码
     */
    getRegionSort(regionCode) {
      const region = this.managementAreaOptions.find(item => item.enCode === regionCode)
      const sortCode = region ? region.sortCode || 999 : 999
      // 强制转换为数字类型
      const numericSortCode = Number(sortCode)
      return isNaN(numericSortCode) ? 999 : numericSortCode
    },

    /**
     * 刷新数据并通知父组件
     */
    refreshData() {
      this.loadGuidanceData()
      this.$emit('refresh')
    }
  }
}
</script>

<style scoped>
@import './shared-table-styles.scss';
</style>
